package com.common.controller.base;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.core.convert.converter.Converter;

import com.common.util.ConstantDefine;
import com.common.util.StringUtil;

/**
 * 将String格式的日期转为Date
 * 
 * @author charly
 *
 */
public class DateConverter implements Converter<String, Date> {
	private Logger logger = Logger.getLogger(this.getClass());
	@Override
	public Date convert(String source) {
		String pattern = null;
		if (StringUtil.isBlank(source)) {
			return null;
		} else if (source.length() == 10) {
			pattern = ConstantDefine.YMD;
		} else {
			pattern = ConstantDefine.YMD_HMS;
		}
		
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		dateFormat.setLenient(false);
		try {
			return dateFormat.parse(source);
		} catch (ParseException e) {
			logger.error("String convert to Date,format is incorrect###"+e.getMessage());
		}
		return null;
	}
}
